﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using Utils;
using Wrapper;
using DotNet.Utilities;

namespace Logic
{
    /// <summary>
    /// 店员积分 网站登录，推荐逻辑处理类
    /// </summary>
    public class DYJF1Logic
    {
        private string LOGIN_SHOW_URL = "http://www.ha.10086.cn/tiyan/channel/tologon.action";

        private string LOGIN_CHECKIMG_URL = "https://ha.ac.10086.cn/checkImage";

        private string LOGIN_URL = "https://ha.ac.10086.cn/login";

        //http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action?loginPhoneNo=13526851141&errorCode=4001&authTimes=2
        private string LOGIN_FAIL_URL = "http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action";

        private string LOGIN_SUC_URL = "http://www.ha.10086.cn/tiyan/SSOClient/ssoLogin.action?a=validateSSO&n=channel";

        private string SSOPOST_URL = "https://ha.ac.10086.cn/SSOPOST";

        private string IMPLICITLOGIN_URL = "http://www.ha.10086.cn/tiyan/SSOClient/implicitLogin.action";

        private string VALIDATESSO_URL = "http://www.ha.10086.cn/tiyan/channel/validateSSO.action";

        HttpHelper httpUtils = null;
        private string sid;
        private string referer = "";

        private string imgPath = "dyjfimg\\";

        public DYJF1Logic(string _sid)
        {
            sid = _sid;
            httpUtils = new HttpHelper();

            if (!Directory.Exists(imgPath))
            {
                Directory.CreateDirectory(imgPath);
            }
            imgPath = imgPath + DateTime.Now.ToString("yyyyMMdd") + "\\";
            if (!Directory.Exists(imgPath))
            {
                Directory.CreateDirectory(imgPath);
            }
        }

        public string Get_Login_Show()
        {
            /*
             <input type="hidden" name="IDToken2" value="2">
			<input type="hidden" name="authType" value="userPass">
			<input type="hidden" name="SysSeqNO" value="5000">
			<input type="hidden" name="goto" value='http://www.ha.10086.cn/tiyan/SSOClient/ssoLogin.action?a=validateSSO&n=channel'/>
			<input type="hidden" name="BackURL" value='http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action'/>
			<input type="hidden" name="SPID" value='http://www.ha.10086.cn/tiyan'/>
             */
            HttpItem item = new HttpItem()
            {
                URL = LOGIN_SHOW_URL,
                Method = "get"
            };
            string result = httpUtils.GetHtml(item).Html;
            return result;
        }

        public bool DownImage()
        {
            referer = LOGIN_SHOW_URL;

            HttpItem item = new HttpItem()
            {
                URL = LOGIN_CHECKIMG_URL,//URL     必需项
                Encoding = null,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                ResultType = ResultType.Byte
            };

            //得到HTML代码
            HttpResult result = httpUtils.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //表示访问成功，具体的大家就参考HttpStatusCode类
            }
            //表示StatusCode的文字说明与描述
            string statusCodeDescription = result.StatusDescription;
            //把得到的Byte转成图片

            File.WriteAllBytes(imgPath + sid + ".jpg", result.ResultByte);

            return true;
        }

        /// <summary>
        /// 识别验证码
        /// </summary>
        /// <returns></returns>
        public CodeInfo RecognizeRadon()
        {
            string fullPath = imgPath + sid + ".jpg";
            return WrapperUtil.getInstance().recognize(fullPath);
        }

        //成功则跳转ssopost页面，失败跳转dianyuanFai.action
        public bool Login(string phone, string pwd, string radom)
        {
            bool suc = false;
            StringBuilder sb = new StringBuilder("IDToken1=" + phone);
            sb.Append("&IDToken3=" + pwd);
            sb.Append("&IDToken4=" + radom);
            sb.Append("&IDToken2=2");
            sb.Append("&authType=userPass");
            sb.Append("&SysSeqNO=5000");

            sb.Append("&goto=" + HttpUtility.UrlEncode("http://www.ha.10086.cn/tiyan/SSOClient/ssoLogin.action?a=validateSSO&n=channel", Encoding.UTF8));
            sb.Append("&BackURL=" + HttpUtility.UrlEncode("http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action", Encoding.UTF8));
            sb.Append("&SPID=" + HttpUtility.UrlEncode("http://www.ha.10086.cn/tiyan", Encoding.UTF8));

            HttpItem item = new HttpItem()
            {
                URL = LOGIN_URL,//URL     必需项
                Method = "post",
                Postdata = sb.ToString(),
                PostDataType= PostDataType.String,
                Referer = referer
                
            };

            string loginRespHtml = httpUtils.GetHtml(item).Html;

            string SAMLRequest = "";
            string RelayState = "";

            //解析 登录的返回数据
            AnalizeLoginData(loginRespHtml, out SAMLRequest, out RelayState);
            if (SAMLRequest == "" || RelayState == "")
            {
                Log.PrintLog("第一层验证错误：" + loginRespHtml);
            }
            else
            {
                sb = new StringBuilder("SAMLRequest=" + SAMLRequest);
                sb.Append("&RelayState=" + RelayState);

                item = new HttpItem()
                {
                    URL = SSOPOST_URL,//URL     必需项
                    Method = "post",
                    Postdata = sb.ToString(),
                    PostDataType = PostDataType.String,
                    Referer = referer
                };

                string SSORespHtml = httpUtils.GetHtml(item).Html;

                //string SAMLart = "";
                //AnalizeSSOData(SSORespHtml, out SAMLart, out RelayState);

                //if (SAMLart == "" || RelayState == "")
                //{
                //    Log.PrintLog("第二层验证错误：" + SSORespHtml);
                //}
                //else
                //{
                //    sb = new StringBuilder("SAMLart=" + SAMLart);
                //    sb.Append("RelayState" + RelayState);

                //    string lastLoginHtml = httpUtils.DoPost(IMPLICITLOGIN_URL, sb.ToString(), referer);

                //    if (!checkResult(lastLoginHtml))
                //    {
                //        Log.PrintLog("第三层验证错误：" + lastLoginHtml);
                //    }
                //    else
                //    {
                //        suc = true;
                //    }
                //}
            }
            return suc;
        }

        public bool checkResult(string loginHtml)
        {
            bool suc = true;
            if (loginHtml.IndexOf("尊敬的") > 0)
            {
                suc = true;
            }
            else
            {
                suc = false;
            }
            return suc;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SSORespHtml"></param>
        /// <param name="SAMLart"></param>
        /// <param name="RelayState"></param>
        public static void AnalizeSSOData(string SSORespHtml, out string SAMLart, out string RelayState)
        {
            SAMLart = "";
            RelayState = "";

            try
            {
                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(File.ReadAllText("a.txt"));

                HtmlNode hidden1 = document.DocumentNode.SelectSingleNode("//input[@name=\"SAMLart\"]");
                HtmlNode hidden2 = document.DocumentNode.SelectSingleNode("//input[@name=\"RelayState\"]");

                if (hidden1 != null)
                {
                    SAMLart = hidden1.GetAttributeValue("value", "");
                }

                if (hidden2 != null)
                {
                    RelayState = hidden2.GetAttributeValue("value", "");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 解析html页面，获取 SAMLRequest 和 RelayState
        /// </summary>
        /// <param name="loginRespHtml"></param>
        /// <param name="SAMLRequest"></param>
        /// <param name="RelayState"></param>
        public static void AnalizeLoginData(string loginRespHtml, out string SAMLRequest, out string RelayState)
        {
            SAMLRequest = "";
            RelayState = "";
            try
            {

                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(loginRespHtml);

                HtmlNode hidden1 = document.DocumentNode.SelectSingleNode("//input[@name=\"SAMLRequest\"]");
                HtmlNode hidden2 = document.DocumentNode.SelectSingleNode("//input[@name=\"RelayState\"]");


                if (hidden1 != null)
                {
                    SAMLRequest = hidden1.GetAttributeValue("value", "");
                }

                if (hidden2 != null)
                {
                    RelayState = hidden2.GetAttributeValue("value", "");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string SSOPost(string SAMLRequest, string RelayState)
        {
            //StringBuilder sb = new StringBuilder("SAMLRequest=" + SAMLRequest);
            //sb.Append("&RelayState=" + RelayState);

            //return httpUtils.DoPost(SSOPOST_URL, sb.ToString(), referer);
            return "";
        }


        private string RECOMMAND_URL = "http://www.ha.10086.cn/tiyan/game/checkMsisdn.action";

        private string RECOMMAND_SENDINFO_URL = "http://www.ha.10086.cn/tiyan/game/sendInfoForClient.action";

        public string Post_Recommand(string phone)
        {
            //referer = "http://www.ha.10086.cn/tiyan/channel/salearea.action";
            //string param = "toMsisdn=" + phone;
            //string result = httpUtils.DoPost(RECOMMAND_URL, param, referer);
            //return result;
            return "";
        }

        public string Post_SendInfo(string phone, string busCode, string busName)
        {
            //StringBuilder sb = new StringBuilder();
            //sb.Append("busCode=" + busCode);
            //sb.Append("&toMsisdn=" + phone);
            //sb.Append("&busName=" + HttpUtility.UrlEncode(busName));
            //string result = httpUtils.DoPost(RECOMMAND_SENDINFO_URL, sb.ToString(), referer);
            //return result;
            return "";
        }
    }
}
